<template>
  <div class="event-list-container">
    <!-- 静态欢迎内容，始终显示 -->
    <div class="welcome-banner" v-if="!eventList.length && loading">
      <div class="welcome-banner-content">
        <h2>欢迎访问活动票务商城</h2>
        <p>正在为您加载精彩活动...</p>
        <el-skeleton :rows="3" animated />
      </div>
    </div>
    
    <!-- 筛选栏 -->
    <div class="filter-section">
      <el-row>
        <el-col :span="24">
          <el-input
            v-model="queryParams.keyword"
            placeholder="搜索活动"
            clearable
            @keyup.enter="handleSearch"
            @clear="handleSearch">
            <template #suffix>
              <el-icon class="el-input__icon" @click="handleSearch"><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
      </el-row>
    </div>

    <!-- 活动列表 -->
    <div class="event-grid">
      <template v-if="eventList.length > 0">
        <el-row :gutter="20">
          <el-col v-for="event in eventList" :key="event.id" :xs="24" :sm="12" :md="8" :lg="6" class="event-item-col">
            <el-card class="event-card" shadow="hover" @click="navigateToDetail(event.id)">
              <div class="event-cover">
                <img :src="event.cover" :alt="event.title" />
                <div class="event-category">{{ event.category }}</div>
              </div>
              <div class="event-info">
                <h3 class="event-title">{{ event.title }}</h3>
                <div class="event-meta">
                  <div class="event-time">
                    <el-icon><Calendar /></el-icon>
                    <span>{{ formatDate(event.startTime) }}</span>
                  </div>
                  <div class="event-location">
                    <el-icon><Location /></el-icon>
                    <span>{{ event.location }}</span>
                  </div>
                </div>
                <div class="event-tags">
                  <el-tag v-for="tag in event.tags" :key="tag" size="small">{{ tag }}</el-tag>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </template>
      <template v-else-if="!loading">
        <!-- 无数据状态 -->
        <el-empty description="暂无活动" v-if="!loading">
          <template #description>
            <p>当前没有可显示的活动</p>
            <p>请稍后再来查看或尝试其他筛选条件</p>
          </template>
          <el-button type="primary" @click="resetFilter">重置筛选</el-button>
        </el-empty>
      </template>
      <template v-else>
        <!-- 加载状态占位 -->
        <div class="event-card-skeletons">
          <el-skeleton-item v-for="i in 6" :key="i" variant="rect" style="width: 240px; height: 320px; margin: 10px;"/>
        </div>
      </template>
    </div>

    <!-- 分页器 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[8, 12, 24, 36]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Calendar, Location } from '@element-plus/icons-vue'
import { getFrontEventList, getEventCategories } from '@/utils/apiAdapter'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 12,
  keyword: '',
  category: '',
  tag: '',
  sortType: 1 // 默认最新上线
})

// 数据绑定
const eventList = ref([])
const total = ref(0)
const categories = ref([])
const tags = ref([])
const loading = ref(false) // 添加加载状态

// 获取分类和标签数据
const fetchCategories = async () => {
  try {
    const res = await getEventCategories()
    categories.value = res.data || []
    
    // 提取所有标签
    const allTags = []
    categories.value.forEach(category => {
      if (category.tags && Array.isArray(category.tags)) {
        allTags.push(...category.tags)
      }
    })
    tags.value = [...new Set(allTags)] // 去重
  } catch (error) {
    console.error('获取分类标签失败:', error)
  }
}

// 获取活动列表数据
const fetchEventList = async (retryCount = 2, overrideParams = null) => {
  if (loading.value) return // 防止重复请求
  
  loading.value = true
  try {
    console.log('开始获取活动列表...')
    
    // 显式移除可能存在的错误消息
    document.querySelectorAll('.el-message').forEach(el => el.remove())
    
    // 使用传入的参数或默认参数
    const requestParams = overrideParams || queryParams.value
    console.log('活动列表请求参数:', requestParams)
    
    const res = await getFrontEventList(requestParams)
    console.log('活动列表API响应:', res)
    
    // 深度检查响应结构
    if (res) {
      // 兼容多种可能的返回结构
      if (res.data && Array.isArray(res.data)) {
        // 直接是数组的情况
        eventList.value = res.data || []
        total.value = res.data.length || 0
        console.log('活动列表获取成功(数组格式)，条数:', eventList.value.length)
      } else if (res.data && res.data.records && Array.isArray(res.data.records)) {
        // 标准分页对象格式：{records: [], total: 10}
        eventList.value = res.data.records || []
        total.value = res.data.total || 0
        console.log('活动列表获取成功(分页对象格式)，条数:', eventList.value.length)
      } else if (res.data && typeof res.data === 'object') {
        // 尝试从响应中提取任何可能的数组数据
        const possibleArrayKeys = ['list', 'items', 'events', 'data', 'content']
        let foundData = false
        
        for (const key of possibleArrayKeys) {
          if (res.data[key] && Array.isArray(res.data[key])) {
            eventList.value = res.data[key]
            total.value = res.data.total || res.data.count || res.data[key].length || 0
            console.log(`活动列表获取成功(键${key})，条数:`, eventList.value.length)
            foundData = true
            break
          }
        }
        
        if (!foundData) {
          // 如果没有找到数组，把整个data当作单个对象处理
          console.warn('未找到数组数据，尝试使用整个data对象:', res.data)
          if (Object.keys(res.data).length > 0) {
            // 将对象转为数组处理
            const entries = Object.entries(res.data)
              .filter(([key, value]) => typeof value === 'object' && value !== null)
              .map(([key, value]) => ({id: key, ...value}))
            
            if (entries.length > 0) {
              eventList.value = entries
              total.value = entries.length
              console.log('从对象提取的活动列表，条数:', eventList.value.length)
              foundData = true
            }
          }
        }
        
        if (!foundData) {
          console.warn('无法从响应中提取活动列表数据，使用空数组')
          eventList.value = []
          total.value = 0
        }
      } else {
        console.warn('活动列表响应格式异常，使用空数组:', res)
        eventList.value = []
        total.value = 0
      }
    } else {
      console.warn('获取活动列表响应为空，使用空数组')
      eventList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    
    // 判断是否是401错误 - 匿名访问时不重试
    const is401Error = 
      (error.message && error.message.includes('401')) || 
      (error.response && error.response.status === 401)
      
    if (is401Error) {
      console.log('活动列表需要登录访问，尝试使用匿名访问方式重新获取')
      try {
        // 尝试使用强制匿名方式重新获取数据
        const anonymousRes = await getFrontEventList({
          ...requestParams,
          anonymous: true, // 添加匿名访问标记
          _t: Date.now() // 添加时间戳避免缓存
        })
        
        if (anonymousRes && anonymousRes.data) {
          // 处理匿名访问的响应
          if (Array.isArray(anonymousRes.data)) {
            eventList.value = anonymousRes.data
            total.value = anonymousRes.data.length
          } else if (anonymousRes.data.records && Array.isArray(anonymousRes.data.records)) {
            eventList.value = anonymousRes.data.records
            total.value = anonymousRes.data.total || 0
          }
          console.log('匿名访问获取活动列表成功，条数:', eventList.value.length)
          return
        }
      } catch (anonError) {
        console.error('匿名访问获取活动列表也失败:', anonError)
      }
      
      // 如果匿名访问也失败，显示空状态但不显示错误
      eventList.value = []
      total.value = 0
      return
    }
    
    // 添加重试机制
    if (retryCount > 0) {
      console.log(`获取活动列表失败，${retryCount}秒后自动重试...`)
      setTimeout(() => {
        loading.value = false // 重置加载状态，允许重试
        fetchEventList(retryCount - 1, requestParams)
      }, 1000)
      return
    }
    
    // 重试次数用完，静默处理错误
    console.error('活动列表获取最终失败，显示空状态')
    // 防止完全空白，设置一个空数组
    eventList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.value.pageNum = page
  fetchEventList()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  queryParams.value.pageSize = size
  queryParams.value.pageNum = 1
  fetchEventList()
}

// 处理搜索
const handleSearch = () => {
  queryParams.value.pageNum = 1
  fetchEventList()
}

// 导航到活动详情页
const navigateToDetail = (id) => {
  router.push(`/front/event/detail/${id}`)
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 监听排序变化
watch(() => queryParams.value.sortType, () => {
  handleSearch()
})

// 重置筛选条件
const resetFilter = () => {
  queryParams.value.keyword = ''
  handleSearch()
}

// 页面加载时获取数据
onMounted(() => {
  console.log('活动列表组件加载')
  
  // 添加延迟是为了确保页面布局已完成初始化
  setTimeout(() => {
    // 直接获取活动列表
    const initialParams = {
      ...queryParams.value,
      anonymous: true,
      _t: Date.now()
    }
    fetchEventList(2, initialParams)
  }, 300)
  
  // 监听自定义刷新事件
  window.addEventListener('refresh-event-list', () => {
    console.log('接收到活动列表刷新事件')
    fetchEventList(2, { ...queryParams.value, anonymous: true }) // 重新获取活动列表，指定匿名访问
  })
})

// 组件卸载时清理事件监听
onUnmounted(() => {
  window.removeEventListener('refresh-event-list', () => {})
})
</script>

<style scoped>
.event-list-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.welcome-banner {
  background: linear-gradient(135deg, #5e5ce6, #007aff);
  color: white;
  border-radius: 24px;
  padding: 40px;
  margin-bottom: 40px;
  text-align: center;
  box-shadow: 0 8px 30px rgba(94, 92, 230, 0.2);
}

.welcome-banner h2 {
  font-size: 40px;
  font-weight: 700;
  margin-bottom: 16px;
  letter-spacing: -0.5px;
}

.welcome-banner p {
  font-size: 18px;
  margin-bottom: 24px;
  opacity: 0.9;
}

.filter-section {
  margin-bottom: 30px;
}

.filter-section :deep(.el-input__wrapper) {
  background: rgba(0, 0, 0, 0.03);
  border: none;
  box-shadow: none !important;
  border-radius: 12px;
  padding: 8px 16px;
}

.filter-section :deep(.el-input__wrapper:hover) {
  background: rgba(0, 0, 0, 0.05);
}

.filter-section :deep(.el-input__inner) {
  height: 40px;
}

.event-grid {
  margin-bottom: 40px;
}

.event-item-col {
  margin-bottom: 30px;
}

.event-card {
  border-radius: 20px;
  overflow: hidden;
  border: none !important;
  background: #fbfbfd !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  cursor: pointer;
}

.event-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.event-cover {
  position: relative;
  height: 160px;
  overflow: hidden;
}

.event-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.event-card:hover .event-cover img {
  transform: scale(1.05);
}

.event-category {
  position: absolute;
  top: 12px;
  right: 12px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  backdrop-filter: blur(4px);
  -webkit-backdrop-filter: blur(4px);
}

.event-info {
  padding: 20px;
}

.event-title {
  font-size: 18px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0 0 12px;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.event-meta {
  margin-bottom: 16px;
  color: #86868b;
  font-size: 14px;
}

.event-meta > div {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.event-meta .el-icon {
  margin-right: 8px;
  font-size: 16px;
}

.event-meta .event-time .el-icon {
  color: #ff9f0a;
}

.event-meta .event-location .el-icon {
  color: #ff375f;
}

.event-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.event-tags :deep(.el-tag) {
  background: rgba(94, 92, 230, 0.1);
  border: none;
  color: #5e5ce6;
  font-weight: 500;
  border-radius: 8px;
  padding: 0 10px;
}

/* 分页器样式 */
.pagination {
  margin-top: 40px;
  text-align: center;
  background-color: #fbfbfd;
  padding: 16px;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.pagination :deep(.el-pagination) {
  justify-content: center;
}

.pagination :deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #5e5ce6;
}

.pagination :deep(.el-pagination.is-background .el-pager li) {
  border-radius: 50%;
  margin: 0 4px;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
}

/* 骨架屏样式 */
.event-card-skeletons {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 30px;
  padding: 20px;
}

.event-card-skeletons :deep(.el-skeleton__item) {
  border-radius: 20px;
  background-color: #f5f5f7;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .welcome-banner {
    padding: 30px 20px;
  }
  
  .welcome-banner h2 {
    font-size: 32px;
  }

  .welcome-banner p {
    font-size: 17px;
  }

  .event-grid {
    padding: 0 16px;
  }

  .event-item-col {
    margin-bottom: 20px;
  }
}
</style> 